<template>
	<view class="container">
		<!-- 图片上传区域 -->
		<view class="image-upload-section">
			<!-- 已选择的图片列表 -->
			<view class="image-list" v-if="productData.images && productData.images.length > 0">
				<view class="image-item" v-for="(image, index) in productData.images" :key="index">
					<image 
						class="selected-image" 
						:src="image" 
						mode="aspectFill"
						@click="previewImage(image, index)"
					/>
					<view class="delete-btn" @click="deleteImage(index)">
						<text class="delete-icon">×</text>
					</view>
				</view>
			</view>
			
			<!-- 添加图片按钮 -->
			<view class="image-upload" v-else  @click="uploadImage">
				<view class="upload-placeholder">
					<text class="upload-icon">+</text>
					<text class="upload-text">添加图片</text>
				</view>
			</view>
		</view>
		
		<!-- 商品名称输入框 -->
		<view class="form-item">
			<input 
				class="product-name-input"
				type="text"
				placeholder="请输入商品名称"
				v-model="productData.name"
			/>
		</view>
		
		<!-- 商品描述文本区域 -->
		<!-- <view class="form-item">
			<textarea 
				class="product-desc-input"
				placeholder="请输入商品的详细描述，该描述将展示在商品名称的下方，方便用户更详细的了解该商品。"
				v-model="productData.description"
				@input="updateCharCount"
				maxlength="250"
			></textarea>
			<view class="char-count">{{ charCount }}/250</view>
		</view> -->
		
		<!-- 零售价 -->
		<view class="field-item">
			<view class="field-label">
				<text class="label-text">零售价:</text>
			</view>
			<view class="field-input">
				<input 
					class="price-input"
					type="number"
					placeholder="请输入零售价"
					v-model="productData.costPrice"
				/>
				<text class="strike-price-link">划线价</text>
			</view>
		</view>
		
		<!-- 表单字段 -->
		<view class="form-fields">
			<!-- 进货价 -->
			<view class="field-item">
				<view class="field-label">
					<text class="label-text">进货价:</text>
				</view>
				<view class="field-input">
					<input 
						class="price-input"
						type="number"
						placeholder="请输入进货价"
						v-model="productData.price"
					/>
				</view>
			</view>
			
			<!-- 分类 -->
			<view class="field-item">
				<view class="field-label">
					<text class="label-text">分类:</text>
				</view>
				<view class="field-input">
					<view class="picker-container" @click="showCategoryPicker = true">
						<text class="picker-text" :class="{ placeholder: !categoryData.id }">
							{{ categoryData.id ? getCategoryPath(categoryData.id) : '请选择分类' }}
						</text>
						<text class="picker-arrow">▼</text>
					</view>
				</view>
			</view>
			
			<!-- 库存 -->
			<!-- <view class="field-item">
				<view class="field-label">
					<text class="label-text">库存:</text>
				</view>
				<view class="field-input">
					<input 
						class="stock-input"
						type="number"
						v-model="productData.stock"
					/>
				</view>
			</view> -->
			
			<!-- 规格 -->
			<view class="field-item">
				<view class="field-label">
					<text class="label-text">规格:</text>
				</view>
				<view class="field-input">
					<view class="picker-container" @click="showSpecPicker = true">
						<text class="picker-text" :class="{ placeholder: !productData.specification }">
							{{ productData.specification || '请选择规格' }}
						</text>
						<text class="picker-arrow">▼</text>
					</view>
				</view>
			</view>
			
			<!-- 面值 -->
			<view class="field-item">
				<view class="field-label">
					<text class="label-text">面值:</text>
				</view>
				<view class="field-input">
					<view class="picker-container" @click="showFaceValuePicker = true">
						<text class="picker-text" :class="{ placeholder: !productData.faceValue }">
							{{ productData.faceValue || '请选择面值' }}
						</text>
						<text class="picker-arrow">▼</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分类选择器弹窗 -->
		<view v-if="showCategoryPicker" class="picker-modal" @click.stop="showCategoryPicker = false">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">选择分类</text>
					<text class="picker-close" @click.stop="showCategoryPicker = false">×</text>
				</view>
				<view class="picker-body">
					<view 
						v-for="option in categoryOptions"
						:key="option.value"
						class="picker-option"
						:class="{ active: categoryData.id === option.value }"
						@click="selectCategory(option.value)"
					>
						<text>{{ option.label }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 规格选择器弹窗 -->
		<view v-if="showSpecPicker" class="picker-modal" @click.stop="showSpecPicker = false">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">选择规格</text>
					<text class="picker-close" @click.stop="showSpecPicker = false">×</text>
				</view>
				<view class="picker-body">
					<view 
						v-for="option in specOptions"
						:key="option.id || option.name"
						class="picker-option"
						:class="{ active: productData.specification === option.name }"
						@click="selectSpec(option)"
					>
						<text>{{ option.name }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 面值选择器弹窗 -->
		<view v-if="showFaceValuePicker" class="picker-modal" @click.stop="showFaceValuePicker = false">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">选择面值</text>
					<text class="picker-close" @click.stop="showFaceValuePicker = false">×</text>
				</view>
				<view class="picker-body">
					<view 
						v-for="option in faceValueOptions"
						:key="option.id || option.name"
						class="picker-option"
						:class="{ active: productData.faceValue === option.name }"
						@click="selectFaceValue(option)"
					>
						<text>{{ option.name }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-buttons">
			<!-- 保存按钮 -->
			<view class="save-button" @click="saveProduct">
				<text class="save-text">{{ productData.id ? '修改' : '保存' }}</text>
			</view>
			<!-- 删除按钮 -->
			<view class="delete-button" v-if="productData.id" @click="deleteProduct">
				<text class="delete-text">删除</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			charCount: 0,
			productData: {
				id: '',
				name: '',
				price: '',
				costPrice: '', // 进价
				stock: '',
				specification: '', // 规格
				faceValue: '', // 面值
				images: [], // 商品图片列表
				file: '' // 商品图片文件
			},
			categoryData: {
				id: '',
				name: ''
			},
			showCategoryPicker: false,
			categories: [], // 分类列表
			categoryOptions: [], // 选择器选项
			showSpecPicker: false, // 规格选择器显示状态
			specOptions: [], // 规格选项（从字典获取）
			showFaceValuePicker: false, // 面值选择器显示状态
			faceValueOptions: [] // 面值选项（从字典获取）
		}
	},
	onLoad(options) {
		// 加载分类列表
		this.loadCategories()
		// 加载规格字典
		this.loadSpecOptions()
		// 加载面值字典
		this.loadFaceValueOptions()
		
		// 如果有传入的分类ID，从接口加载分类详情
		if (options.category) {
			let category = JSON.parse(options.category)
			this.categoryData.id = category.id
			this.categoryData.name = category.name
		}
		if (options.product) {
			let product = JSON.parse(options.product)
			this.productData.id = product.id
			this.productData.name = product.name
			this.productData.price = product.price
			this.productData.costPrice = product.costPrice || ''
			this.productData.stock = product.stock
			this.productData.specification = product.specification || ''
			this.productData.faceValue = product.faceValue || ''
			this.productData.images = product.images || []
			// 如果有商品数据，设置分类ID
			if (product.categoryId) {
				this.categoryData.id = product.categoryId
			}
		}
		
		//页面标题
		this.title = this.productData.id ? '修改商品' : '添加商品'
		uni.setNavigationBarTitle({
			title: this.title
		})
	},
	methods: {
		// 加载规格字典
		loadSpecOptions() {
			this.$u.api.dictData({dictType: 'spec_type'}).then(res => {
				if (res && Array.isArray(res) && res.length > 0) {
					this.specOptions = res
					// 如果没有规格值，默认选中第一个的name
					if (!this.productData.specification && this.specOptions.length > 0) {
						this.productData.specification = this.specOptions[0].name
					}
				} else {
					this.specOptions = []
				}
			}).catch(err => {
				console.error('获取规格字典失败:', err)
				this.specOptions = []
			})
		},
		
		// 加载面值字典
		loadFaceValueOptions() {
			this.$u.api.dictData({dictType: 'face_value'}).then(res => {
				if (res && Array.isArray(res) && res.length > 0) {
					this.faceValueOptions = res
				} else {
					this.faceValueOptions = []
				}
			}).catch(err => {
				console.error('获取面值字典失败:', err)
				this.faceValueOptions = []
			})
		},
		
		// 加载分类列表
		loadCategories() {
			this.$u.api.productCategory.treeData().then(res => {
				if (res && Array.isArray(res) && res.length > 0) {
					this.categories = res || []
					this.buildCategoryOptions()
				} else if (res && res.list && res.list.length > 0) {
					this.categories = res.list || []
					this.buildCategoryOptions()
				} else {
					this.categories = []
					this.categoryOptions = []
				}
			}).catch(err => {
				console.error('获取分类列表失败:', err)
				this.categories = []
				this.categoryOptions = []
			})
		},
		
		// 构建分类选项（从扁平数据构建树形结构，然后扁平化显示）
		buildCategoryOptions() {
			// 将扁平数据转换为树形结构
			const tree = this.buildTree(this.categories)
			this.categoryOptions = []
			this.flattenCategories(tree, 0, '')
		},
		
		// 将扁平数据转换为树形结构
		buildTree(list) {
			// 如果已经是树形结构，直接返回
			if (list && list.length > 0 && list[0].children !== undefined) {
				return list
			}
			
			const map = {}
			list.forEach(item => {
				item.children = []
				map[item.id] = item
			})
			
			const tree = []
			list.forEach(item => {
				// 使用 parentCode 字段
				const parentCode = item.parentCode || item.parentId || item.parent_id || '0'
				
				if (parentCode === '0' || parentCode === 0 || !parentCode) {
					tree.push(item)
				} else {
					const parent = map[parentCode]
					if (parent) {
						if (!parent.children) {
							parent.children = []
						}
						parent.children.push(item)
					} else {
						tree.push(item)
					}
				}
			})
			
			return tree
		},
		
		// 递归扁平化分类树（用于显示）
		flattenCategories(categories, level, prefix) {
			categories.forEach(category => {
				const label = prefix + category.name
				this.categoryOptions.push({
					label: label,
					value: category.id,
					name: category.name
				})
				
				// 递归处理子分类
				if (category.children && category.children.length > 0) {
					this.flattenCategories(category.children, level + 1, prefix + '　')
				}
			})
		},
		
		// 获取分类路径
		getCategoryPath(categoryId) {
			// 先构建树
			const tree = this.buildTree(this.categories)
			
			const findPath = (categories, targetId, path = []) => {
				for (const category of categories) {
					if (category.id === categoryId) {
						return [...path, category.name].join(' > ')
					}
					if (category.children && category.children.length > 0) {
						const found = findPath(category.children, targetId, [...path, category.name])
						if (found) {
							return found
						}
					}
				}
				return null
			}
			
			return findPath(tree, categoryId) || ''
		},
		
		// 选择分类
		selectCategory(categoryId) {
			const category = this.findCategoryById(this.buildTree(this.categories), categoryId)
			if (category) {
				this.categoryData.id = category.id
				this.categoryData.name = category.name
			}
			this.showCategoryPicker = false
		},
		
		// 在分类树中查找指定ID的分类
		findCategoryById(categories, categoryId) {
			for (const category of categories) {
				if (category.id === categoryId) {
					return category
				}
				if (category.children && category.children.length > 0) {
					const found = this.findCategoryById(category.children, categoryId)
					if (found) {
						return found
					}
				}
			}
			return null
		},
		
		// 选择规格
		selectSpec(spec) {
			this.productData.specification = spec.name
			this.showSpecPicker = false
		},
		
		// 选择面值
		selectFaceValue(faceValue) {
			this.productData.faceValue = faceValue.name
			this.showFaceValuePicker = false
		},
		
		uploadImage() {
			this.chooseSingleImage()
		},
		
		chooseSingleImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					
					this.productData.file = res.tempFiles[0]
					console.log('选择图片成功', this.productData.file)
					
					// 只保存一张图片
					this.productData.images = [res.tempFilePaths[0]]
					
					uni.showToast({
						title: '图片选择成功',
						icon: 'success'
					})
				},
				fail: (err) => {
					console.error('选择图片失败', err)
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 删除图片
		deleteImage(index) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这张图片吗？',
				success: (res) => {
					if (res.confirm) {
						this.productData.images.splice(index, 1)
						this.productData.file = '' // 清空文件对象
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
					}
				}
			})
		},
		
		// 预览图片
		previewImage(current, index) {
			uni.previewImage({
				current: current,
				urls: this.productData.images,
				longPressActions: {
					itemList: ['保存图片', '删除图片'],
					success: (data) => {
						if (data.tapIndex === 1) { // 删除图片
							this.deleteImage(index)
						}
					}
				}
			})
		},
		updateCharCount(e) {
			this.charCount = e.detail.value.length
		},
		addTag() {
			uni.showToast({
				title: '添加标签功能',
				icon: 'none'
			})
		},
		async saveProduct() {
			// 表单验证
			if (!this.productData.name.trim()) {
				uni.showToast({
					title: '请输入商品名称',
					icon: 'none'
				})
				return
			}
			if (!this.productData.costPrice) {
				uni.showToast({
					title: '请输入进价',
					icon: 'none'
				})
				return
			}
			if (!this.productData.price) {
				uni.showToast({
					title: '请输入售价',
					icon: 'none'
				})
				return
			}
			
			if (!this.categoryData.id) {
				uni.showToast({
					title: '请选择商品分类',
					icon: 'none'
				})
				return
			}
			
			// if (!this.productData.stock) {
			// 	uni.showToast({
			// 		title: '请输入商品库存',
			// 		icon: 'none'
			// 	})
			// 	return
			// }
			
			// 显示加载提示
			uni.showLoading({
				title: '保存中...',
				mask: true
			})
			
			try {
				// 准备提交的数据
				const formData = {
					id: this.productData.id,
					name: this.productData.name,
					price: this.productData.price,
					// stock: this.productData.stock,
					categoryId: this.categoryData.id,
					costPrice: this.productData.costPrice,
				}
				
				// 添加可选字段：规格
				if (this.productData.specification && this.productData.specification.trim()) {
					formData.specification = this.productData.specification.trim()
				}
				
				// 添加可选字段：面值
				if (this.productData.faceValue && this.productData.faceValue.trim()) {
					formData.faceValue = this.productData.faceValue.trim()
				}
				
				// 如果有图片文件，使用文件上传
				if (this.productData.file) {
					const res = await this.uploadWithFile(formData)
					this.handleSaveResult(res)
				} else {
					// 没有图片时使用普通接口
					const res = await this.$u.api.productManagement.save(formData)
					this.handleSaveResult(res)
				}
			} catch (error) {
				uni.hideLoading()
				console.error('保存商品失败:', error)
				uni.showToast({
					title: '保存失败，请重试',
					icon: 'none'
				})
			}
		},
		
		// 文件上传方法
		uploadWithFile(formData) {
			return new Promise((resolve, reject) => {
				// 使用 Vuex 中的配置，与其他上传组件保持一致
				let baseUrl = this.vuex_baseUrl
				const adminPath = this.vuex_config.adminPath
				
				// 如果是代理路径（开发环境），uni.uploadFile 不支持代理，需要使用实际服务器地址
				if (baseUrl && (baseUrl.startsWith('/../') || baseUrl.startsWith('/'))) {
					// 从 window.location 获取当前访问的域名
					if (typeof window !== 'undefined' && window.location && window.location.origin) {
						const origin = window.location.origin
						// 如果不是本地地址，使用当前域名
						if (origin.indexOf('localhost') === -1 && origin.indexOf('127.0.0.1') === -1) {
							baseUrl = origin + '/js'
						} else {
							// 开发环境，使用实际服务器地址（从 vue.config.js 的 proxy target）
							baseUrl = 'http://146.56.217.121/js'
						}
					} else {
						// 无法获取 window.location，使用默认服务器地址
						baseUrl = 'http://146.56.217.121/js'
					}
				}
				
				const apiPath = adminPath + '/product/product/save'
				const uploadUrl = baseUrl + apiPath
				
				console.log('基础URL:', baseUrl)
				console.log('管理路径:', adminPath)
				console.log('完整上传URL:', uploadUrl)
				console.log('文件路径:', this.productData.file.path)
				console.log('表单数据:', formData)
				console.log('uView配置:', this.$u.config)
				
				uni.uploadFile({
					url: uploadUrl,
					filePath: this.productData.file.path,
					name: 'file',
					formData: formData,
					header: {
						'Authorization': uni.getStorageSync('token') || ''
					},
					success: (res) => {
						console.log('上传成功:', res)
						try {
							const data = JSON.parse(res.data)
							resolve(data)
						} catch (e) {
							resolve(res.data)
						}
					},
					fail: (err) => {
						console.error('文件上传失败:', err)
						reject(err)
					}
				})
			})
		},
		
		// 处理保存结果
		handleSaveResult(res) {
			uni.hideLoading()
			
			if (res.result === 'true' || res.result === true) {
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
				
				// 延迟返回上一页并刷新
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 1500)
			} else {
				uni.showToast({
					title: res.message || '保存失败',
					icon: 'none'
				})
			}
		},
		deleteProduct() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个商品吗？删除后不可恢复！',
				success: (res) => {
					if (res.confirm) {
						this.confirmDelete()
					}
				}
			})
		},
		confirmDelete() {
			const params = {
				id: this.productData.id
			}
			this.$u.api.productManagement.delete(params).then(res => {
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			}).catch(err => {
				uni.showToast({
					title: '删除失败',
					icon: 'none'
				})
			})
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	padding: 20px;
}

/* 图片上传区域 */
.image-upload-section {
	margin-bottom: 20px;
}

.image-list {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	margin-bottom: 15px;
}

.image-item {
	position: relative;
	width: 120px;
	height: 120px;
	border-radius: 8px;
	overflow: hidden;
}

.selected-image {
	width: 100%;
	height: 100%;
	border-radius: 8px;
}

.delete-btn {
	position: absolute;
	top: 5px;
	right: 5px;
	width: 20px;
	height: 20px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 10;
}

.delete-icon {
	color: #ffffff;
	font-size: 14px;
	font-weight: bold;
	line-height: 1;
}

.image-upload {
	margin-bottom: 10px;
}

.upload-placeholder {
	width: 120px;
	height: 120px;
	border: 2px dashed #e0e0e0;
	border-radius: 8px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #fafafa;
}

.upload-icon {
	font-size: 24px;
	color: #cccccc;
	font-weight: bold;
	margin-bottom: 4px;
}

.upload-text {
	font-size: 12px;
	color: #999999;
}

.image-tip {
	text-align: center;
}

.tip-text {
	font-size: 12px;
	color: #999999;
}

/* 表单项目 */
.form-item {
	margin-bottom: 20px;
	position: relative;
}

.product-name-input {
	width: 100%;
	height: 50px;
	padding: 0 15px;
	border: 1px solid #e0e0e0;
	border-radius: 8px;
	font-size: 12px;
	color: #333333;
	box-sizing: border-box;
}

.product-name-input::placeholder {
	color: #999999;
}

.product-desc-input {
	width: 100%;
	height: 120px;
	padding: 15px;
	border: 1px solid #e0e0e0;
	border-radius: 8px;
	font-size: 16px;
	color: #333333;
	box-sizing: border-box;
	resize: none;
}

.product-desc-input::placeholder {
	color: #999999;
}

.char-count {
	position: absolute;
	bottom: 8px;
	right: 15px;
	font-size: 12px;
	color: #999999;
}

/* 表单字段 */
.form-fields {
	margin-bottom: 120px;
}

.field-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f0f0f0;
}


.field-label {
	width: 80px;
	display: flex;
	align-items: center;
}

.required {
	color: #ff4069;
	font-size: 12px;
	margin-right: 2px;
}

.label-text {
	font-size: 14px;
	color: #333333;
}

.field-input {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.price-input {
	font-size: 12px;
}
.stock-input {
	font-size: 12px;
}

.spec-input {
	font-size: 12px;
}

.strike-price-link {
	width: 50px;
	font-size: 12px;
	color: #007aff;
	margin-left: 10px;
}

.category-display {
	font-size: 12px;
	color: #333333;
}

.picker-container {
	width: 100%;
	height: 40px;
	background-color: #f5f5f5;
	border-radius: 8px;
	padding: 0 10px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-sizing: border-box;
}

.picker-text {
	flex: 1;
	font-size: 12px;
	color: #333333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.picker-text.placeholder {
	color: #999999;
}

.picker-arrow {
	color: #999999;
	font-size: 12px;
	margin-left: 10px;
}

/* 选择器弹窗 */
.picker-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}

.picker-content {
	width: 100%;
	background-color: #ffffff;
	border-radius: 20px 20px 0 0;
	max-height: 70vh;
	display: flex;
	flex-direction: column;
}

.picker-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px;
	border-bottom: 1px solid #f5f5f5;
}

.picker-title {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.picker-close {
	font-size: 24px;
	color: #999999;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.picker-body {
	flex: 1;
	overflow-y: auto;
	padding: 10px 0;
}

.picker-option {
	padding: 15px 20px;
	border-bottom: 1px solid #f5f5f5;
	color: #333333;
	font-size: 14px;
}

.picker-option.active {
	color: #ff4069;
	background-color: #fff8fa;
}

.picker-option:active {
	background-color: #f5f5f5;
}

.add-tag-link {
	font-size: 12px;
	color: #007aff;
}

/* 操作按钮 */
.action-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	flex-direction: row;
	gap: 15px;
	padding: 20px;
	background-color: #ffffff;
	box-sizing: border-box;
	z-index: 999;
}

/* 保存按钮 */
.save-button {
	flex: 1;
	height: 50px;
	background-color: #ff4069;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.save-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: 500;
}

/* 删除按钮 */
.delete-button {
	flex: 1;
	height: 50px;
	background-color: #ff4069;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.delete-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: 500;
}
</style>
